//package cn.genmer.test.security.tagMatch.locationtagtokenizer;
//
//import cn.genmer.test.security.tagMatch.LocationTagTokenizer;
//import com.alibaba.fastjson.JSON;
//import com.alibaba.nacos.api.config.annotation.NacosValue;
//import com.zto56.address.dal.mapper.LocationTagMapper;
//import com.zto56.address.dal.po.LocationTagPO;
//import com.zto56.address.service.bo.LocationTagTokenizerMessageBO;
//import com.zto56.address.service.convert.Converter;
//import com.zto56.address.service.core.LocationTagTokenizerService;
//import com.zto56.address.service.dto.LocationTagTokenizerDTO;
//import com.zto56.address.service.util.AddressUtil;
//import com.zto56.cuckoo.orm.annotation.Datasource;
//import lombok.extern.slf4j.Slf4j;
//import org.springframework.beans.factory.annotation.Autowired;
//import org.springframework.kafka.core.KafkaTemplate;
//import org.springframework.stereotype.Service;
//import org.springframework.util.CollectionUtils;
//import org.springframework.util.StringUtils;
//
//import javax.annotation.PostConstruct;
//import java.util.Comparator;
//import java.util.List;
//import java.util.Map;
//import java.util.stream.Collectors;
//
//
//@Slf4j
//@Service
//public class LocationTagTokenizerServiceImpl implements LocationTagTokenizerService {
//
//    @Autowired
//    LocationTagTokenizer tokenizer;
//
//    @Autowired
//    LocationTagMapper locationTagMapper;
//
//    @Autowired
//    private KafkaTemplate<String, String> kafkaTemplate;
//
//    @NacosValue("${location.tag.tokenizer.sync.topic}")
//    private String topic;
//
//
//    @Override
//    @Datasource("slaveDataSource")
//    public LocationTagTokenizerDTO match(String address, String source) {
//        long start = System.currentTimeMillis();
//        List<Address> addressList = tokenizer.tokenize(address, source);
//        if (CollectionUtils.isEmpty(addressList)) {
//            log.info("LocationTagTokenizer 匹配不到关键字, address: {}, source: {}", address, source);
//            return null;
//        }
//
//        List<Long> idList = addressList.stream().map(Address::getId).map(Long::valueOf).collect(Collectors.toList());
//
//
//        List<LocationTagPO> locationTagPOList = locationTagMapper.findByIdIn(idList);
//        if (CollectionUtils.isEmpty(locationTagPOList)) {
//            log.info("LocationTagTokenizer 匹配不到id数据, id: {}, address: {}, source: {}", idList, address, source);
//            return null;
//        }
//
//        locationTagPOList = locationTagPOList.stream()
//                .peek(po -> {
//                    po.setProvinceName(AddressUtil.removeSuffix(po.getProvinceName(), "省"));
//                    po.setCityName(AddressUtil.removeSuffix(po.getCityName(), "市"));
//                    po.setCountyName(AddressUtil.removeSuffix(po.getCountyName(), "区", "县"));
//                    po.setTownName(AddressUtil.removeSuffix(po.getTownName(), "镇", "街道"));
//                    po.setVillageName(AddressUtil.removeSuffix(po.getVillageName(), "村", "组"));
//                })
//                .filter(po -> {
//                    int minMatchLevel = po.getMinMatchLevel() != null ? po.getMinMatchLevel() : Integer.MAX_VALUE;
//
//                    switch (minMatchLevel) {
//                        case 6: // 村组级别
//                            if (!StringUtils.hasText(po.getVillageName()) || !address.contains(po.getVillageName())) {
//                                return false;
//                            }
//                        case 5: // 乡镇/街道级别
//                            if (!StringUtils.hasText(po.getTownName()) || !address.contains(po.getTownName())) {
//                                return false;
//                            }
//                        case 4: // 区县级别
//                            if (!StringUtils.hasText(po.getCountyName()) || !address.contains(po.getCountyName())) {
//                                return false;
//                            }
//                        case 3: // 城市级别
//                            if (!StringUtils.hasText(po.getCityName()) || !address.contains(po.getCityName())) {
//                                return false;
//                            }
//                        case 2: // 省份级别
//                            if (!StringUtils.hasText(po.getProvinceName()) || !address.contains(po.getProvinceName())) {
//                                return false;
//                            }
//                        default:
//                            // 其他情况忽略检查
//                            break;
//                    }
//
//                    return address.contains(po.getProvinceName()) &&
//                            address.contains(po.getCityName()) &&
//                            address.contains(po.getCountyName()) &&
//                            address.contains(po.getTownName());
//                })
//                .collect(Collectors.toList());
//
//        if (CollectionUtils.isEmpty(locationTagPOList)) {
//            log.info("LocationTagTokenizer 地址中没有包含对应的行政区, address: {}, source: {}", address, source);
//            return null;
//        }
//
//        Map<String, Integer> addressLengthMap = addressList.stream()
//                .collect(Collectors.toMap(
//                        Address::getId,
//                        addr -> addr.getAddress().length()
//                ));
//        Comparator<LocationTagPO> comparator = Comparator
//                .comparing(LocationTagPO::getMinMatchLevel, Comparator.reverseOrder())
//                .thenComparing(locationTagPO -> addressLengthMap.getOrDefault(locationTagPO.getId().toString(), 0), Comparator.reverseOrder())
//                .thenComparing(LocationTagPO::getUpdatedTime, Comparator.reverseOrder());
//
//        locationTagPOList = locationTagPOList.stream()
//                .sorted(comparator)
//                .collect(Collectors.toList());
//        long end = System.currentTimeMillis();
//        long duration = end - start;
//        log.info("LocationTagTokenizerServiceImpl.match 耗时: {} ms", duration);
//
//        return Converter.INSTANCE.convertLocationTagPOTOLocationTagDTO(locationTagPOList.get(0));
//    }
//
//
//    @Override
//    public Boolean saveLocal(LocationTagPO oldPO, LocationTagPO newPO) {
//        List<Address> oldAddressList = tokenizer.convertLocationTagPOToAddressList(oldPO);
//        for (Address address : oldAddressList) {
//            tokenizer.deleteAddress(address.getAddress(), address.getSource());
//        }
//
//        List<Address> newAddressList = tokenizer.convertLocationTagPOToAddressList(newPO);
//        for (Address address : newAddressList) {
//            tokenizer.addAddressToTrie(address);
//        }
//        return true;
//    }
//
//    @Override
//    public Boolean deleteLocal(LocationTagPO po) {
//        List<Address> oldAddressList = tokenizer.convertLocationTagPOToAddressList(po);
//        for (Address address : oldAddressList) {
//            tokenizer.deleteAddress(address.getAddress(), address.getSource());
//        }
//        return true;
//    }
//
//    @Override
//    public Boolean addLocal(LocationTagPO po) {
//        List<Address> newAddressList = tokenizer.convertLocationTagPOToAddressList(po);
//        for (Address address : newAddressList) {
//            tokenizer.addAddressToTrie(address);
//        }
//        return true;
//    }
//
//    @Override
//    public void loadData() {
//
//    }
//
//    @Override
//    public Boolean save(LocationTagPO oldPO, LocationTagPO newPO) {
//        LocationTagTokenizerMessageBO bo = new LocationTagTokenizerMessageBO();
//        bo.setAction("save");
//        bo.setOldLocationPO(oldPO);
//        bo.setNewLocationPO(newPO);
//        log.info("LocationTagTokenizer.save: {}", bo);
//        kafkaTemplate.send(topic, JSON.toJSONString(bo));
//        return true;
//    }
//
//    @Override
//    public Boolean delete(LocationTagPO po) {
//        LocationTagTokenizerMessageBO bo = new LocationTagTokenizerMessageBO();
//        bo.setAction("delete");
//        bo.setOldLocationPO(po);
//        log.info("LocationTagTokenizer.delete: {}", bo);
//        kafkaTemplate.send(topic, JSON.toJSONString(bo));
//        return true;
//    }
//
//    @Override
//    public Boolean add(LocationTagPO po) {
//        LocationTagTokenizerMessageBO bo = new LocationTagTokenizerMessageBO();
//        bo.setAction("add");
//        bo.setNewLocationPO(po);
//        log.info("LocationTagTokenizer.add: {}", bo);
//        kafkaTemplate.send(topic, JSON.toJSONString(bo));
//        return true;
//    }
//
//    @Datasource("slaveDataSource")
//    public void test2() {
//        try {
////            System.out.println("开始add逻辑测试");
////            LocationTagPO locationTagPO = locationTagMapper.findById(90000037751L);
////            add(locationTagPO);
////            System.out.println("暂停5秒");
////            Thread.sleep(5000); // 或者使用 TimeUnit.SECONDS.toMillis(10)
////            printTokenize("浙江省嘉兴市海宁市栋梁路118号中通快运", "gis");
////
////            System.out.println("开始save逻辑测试");
////            LocationTagPO locationTagPO2 = new LocationTagPO();
////            copyProperties(locationTagPO, locationTagPO2);
////            locationTagPO2.setName("栋梁路120号中通快运");
////            save(locationTagPO, locationTagPO2);
////            System.out.println("暂停5秒");
////            Thread.sleep(5000); // 或者使用 TimeUnit.SECONDS.toMillis(10)
////            printTokenize("浙江省嘉兴市海宁市栋梁路120号中通快运", "gis");
//
//
////            System.out.println("开始删除逻辑测试");
////            delete(locationTagPO2);
////            System.out.println("暂停5秒");
////            Thread.sleep(5000); // 或者使用 TimeUnit.SECONDS.toMillis(10)
//            printTokenize("浙江省杭州市桐庐县测试关键字5", "gis");
//
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//    }
//
//    private void printTokenize(String address, String source) {
//        long start = System.currentTimeMillis();
//        LocationTagTokenizerDTO match = match(address, source);
//        long end = System.currentTimeMillis();
//        long duration = end - start;
//        log.info("原地址: {}", address);
//        log.info("分词结果: {}", match);
//        log.info("耗时: {} ms", duration);
//    }
//
//    @PostConstruct
//    public void init() {
//        long start = System.currentTimeMillis();
//        tokenizer.initData();
//        long end = System.currentTimeMillis();
//        long duration = end - start;
//        log.info("LocationTagTokenizer 坐标关键字数据加载完成, 耗时: {} ms", duration);
//    }
//}
